﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using AzureProvider.ssdsClient;
using System.Globalization;
using BlogEngine.Core;

namespace AzureProvider.SoupMethods
{
    public class MembershipUser2 
    {
        public string Id;
        public string Password;
        public MembershipUser MembershipUser;
    }

    public class MembershipUserMethods : BaseMethods 
    {
        public static string Kind = "MembershipUser";

        protected override string containerId
        {
            get { return "UserContainer"; }
        }

        protected override string kind
        {
            get { return Kind ; }
        }

        public MembershipUser2 GetMembershipUser(string UserName)
        {
            List<Entity> ents = GetEntities(UserName);
            if (ents != null && ents.Count > 0)
            {
                return (MembershipUser2)CreateObject(ents.First());
            }
            else
            {
                return null;
            }
        }

        public MembershipUser2 GetMembershipUserByEmail(string Email)
        {
            List<Entity> ents = GetEntitiesByEmail(Email);
            if (ents!= null && ents.Count > 0)
            {
                return (MembershipUser2)CreateObject(ents.First());
            }
            else
            {
                return null;
            }
        }

        protected virtual List<Entity> GetEntities(string UserName)
        {
            string errMessage;
            var qry = "from e in entities where e.Kind == \"" + kind + "\" && e[\"UserName\"]==\"" + UserName + "\"  select e";
            List<Entity> ents =  GetEntities(qry, out errMessage);
            return ents;
        }

        protected virtual List<Entity> GetEntitiesByEmail(string Email)
        {
            string errMessage;
            var qry = "from e in entities where e.Kind == \"" + kind + "\" && e[\"Email\"]==\"" + Email + "\"  select e";
            List<Entity> ents = GetEntities(qry, out errMessage);
            return ents;
        }

        protected override Entity CreateEntity(object Object)
        {
            MembershipUser2 myobj = (MembershipUser2)Object;
            
            var entity = new Entity()
            {
                Id = myobj.Id ,
                Kind = kind
            };

            entity.Properties = new Dictionary<string, object>();
            entity.Properties.Add("Password", myobj.Password);

            //entity.Properties.Add("ProviderName", myobj.MembershipUser.ProviderName);
            entity.Properties.Add("ProviderName", "AzureMembershipProvider");
            entity.Properties.Add("UserName", myobj.MembershipUser.UserName);
            entity.Properties.Add("ProviderUserKey", myobj.MembershipUser.ProviderUserKey);
            entity.Properties.Add("Email", string.IsNullOrEmpty(myobj.MembershipUser.Email) ? "" : myobj.MembershipUser.Email);

            entity.Properties.Add("PasswordQuestion",string.IsNullOrEmpty(myobj.MembershipUser.PasswordQuestion)?"":myobj.MembershipUser.PasswordQuestion);
            entity.Properties.Add("Comment", string.IsNullOrEmpty(myobj.MembershipUser.Comment) ? "" : myobj.MembershipUser.Comment);
            entity.Properties.Add("IsApproved", myobj.MembershipUser.IsApproved);
            entity.Properties.Add("IsLockedOut", myobj.MembershipUser.IsLockedOut);

            entity.Properties.Add("CreationDate",
                myobj.MembershipUser.CreationDate.AddHours(-BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));
            entity.Properties.Add("LastLoginDate",
                myobj.MembershipUser.LastLoginDate.AddHours(-BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));

            entity.Properties.Add("LastActivityDate",
                myobj.MembershipUser.LastActivityDate.AddHours(-BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));
            entity.Properties.Add("LastPasswordChangedDate",
                myobj.MembershipUser.LastPasswordChangedDate.AddHours(-BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));

            entity.Properties.Add("LastLockoutDate",
                myobj.MembershipUser.LastLockoutDate.AddHours(-BlogSettings.Instance.Timezone).ToString("yyyy-MM-dd HH:mm:ss",
                CultureInfo.InvariantCulture));

            return entity;

            //MembershipUser user = new MembershipUser(
            //                        Name,                       // ProviderName
            //                        userName,                   // UserName
            //                        userName,                   // ProviderUserKey
            //                        email,                      // Email
            //                        String.Empty,               // PasswordQuestion
            //                        String.Empty,               // Comment
            //                        true,                       // IsApproved
            //                        false,                      // IsLockedOut
            //                        DateTime.Now,               // CreationDate
            //                        lastLogin,                  // LastLoginDate
            //                        DateTime.Now,               // LastActivityDate
            //                        DateTime.Now,               // LastPasswordChangedDate
            //                        new DateTime(1980, 1, 1)    // LastLockoutDate
            //                    );

        }

        public override object CreateObject(Entity Entity)
        {
            //string ProviderName = (string)Entity.Properties.Single(tt => tt.Key == "ProviderName").Value;                      // ProviderName
            //string UserName = (string)Entity.Properties.Single(tt => tt.Key == "UserName").Value;// UserName
            //string ProviderUserKey = (string)Entity.Properties.Single(tt => tt.Key == "ProviderUserKey").Value;                   // ProviderUserKey
            //string Email = (string)Entity.Properties.Single(tt => tt.Key == "Email").Value;                     // Email
            //string PasswordQuestion = (string)Entity.Properties.Single(tt => tt.Key == "PasswordQuestion").Value;               // PasswordQuestion
            //string Comment = (string)Entity.Properties.Single(tt => tt.Key == "Comment").Value;               // Comment
            //bool IsApproved = (bool)Entity.Properties.Single(tt => tt.Key == "IsApproved").Value;                       // IsApproved
            //bool IsLockedOut = (bool)Entity.Properties.Single(tt => tt.Key == "IsLockedOut").Value;                      // IsLockedOut
            //DateTime CreationDate = DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "CreationDate").Value);               // CreationDate
            //DateTime LastLoginDate = DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastLoginDate").Value);                  // LastLoginDate
            //DateTime LastActivityDate = DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastActivityDate").Value);               // LastActivityDate
            //DateTime LastPasswordChangedDate = DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastPasswordChangedDate").Value);               // LastPasswordChangedDate
            //DateTime LastLockoutDate = DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastLockoutDate").Value);   // LastLockoutDate

            MembershipUser MembershipUser1 = new MembershipUser
                (
                //Id = new Guid(Entity.Id),
                //ProviderName = (string)Entity.Properties.Single(tt => tt.Key == "ProviderName").Value,

                (string)Entity.Properties.Single(tt => tt.Key == "ProviderName").Value,                       // ProviderName
                (string)Entity.Properties.Single(tt => tt.Key == "UserName").Value,                   // UserName
                (string)Entity.Properties.Single(tt => tt.Key == "ProviderUserKey").Value,                   // ProviderUserKey
                (string)Entity.Properties.Single(tt => tt.Key == "Email").Value,                      // Email
                (string)Entity.Properties.Single(tt => tt.Key == "PasswordQuestion").Value,               // PasswordQuestion
                (string)Entity.Properties.Single(tt => tt.Key == "Comment").Value,               // Comment
                (bool)Entity.Properties.Single(tt => tt.Key == "IsApproved").Value,                       // IsApproved
                (bool)Entity.Properties.Single(tt => tt.Key == "IsLockedOut").Value,                      // IsLockedOut
                DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "CreationDate").Value),               // CreationDate
                DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastLoginDate").Value),                  // LastLoginDate
                DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastActivityDate").Value),               // LastActivityDate
                DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastPasswordChangedDate").Value),               // LastPasswordChangedDate
                DateTime.Parse((string)Entity.Properties.Single(tt => tt.Key == "LastLockoutDate").Value)    // LastLockoutDate
                );

            MembershipUser2 myobj = new MembershipUser2
            {
                Id = Entity.Id,
                Password = (string)Entity.Properties.Single(tt => tt.Key == "Password").Value,
                MembershipUser = MembershipUser1
            };

            return myobj;

        }

        public string[] GetRolesForUser(string UserName)
        {
            string errMessage;
            string qry = string.Format(
                @"from u in entities.OfKind(""{0}"") 
                    where  u[""UserName""]==""{3}""
                    from  ur in entities.OfKind(""{1}"") 
                    where ur[""UserID""] == u.Id  
                    from  r in entities.OfKind(""{2}"") 
                    where ur[""RoleID""] == r.Id 
                select r
                "
                , MembershipUserMethods.Kind
                , UserRolesMethods.Kind
                , RolesMethods.Kind
                , UserName);

            return GetEntities(qry, out errMessage).Select(ee=>(string)ee.Properties.Single(tt => tt.Key == "RoleName").Value).ToArray<string>() ;

        }

        
    }
}
